package main

import (
	"flag"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"alfred/api"
	"alfred/database"
	"alfred/executor"
	"alfred/notification"
	"alfred/webhook"

	"github.com/gin-gonic/gin"
)

func main() {
	// 命令行参数
	var (
		port          = flag.String("port", "9291", "服务端口")
		dbPath        = flag.String("db", "./alfred.db", "SQLite数据库文件路径")
		workDir       = flag.String("workdir", "./workspace", "工作目录路径")
		webhookSecret = flag.String("webhook-secret", "", "GitLab Webhook密钥")
		mode          = flag.String("mode", "release", "运行模式: debug, release")
	)
	flag.Parse()

	// 设置Gin模式
	if *mode == "debug" {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}

	// 初始化数据库
	db, err := database.NewDB(*dbPath)
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}
	defer db.Close()

	// 初始化数据库表
	if err := db.InitTables(); err != nil {
		log.Fatalf("Failed to initialize database tables: %v", err)
	}

	// 创建工作目录
	workDirAbs, err := filepath.Abs(*workDir)
	if err != nil {
		log.Fatalf("Failed to get absolute work directory path: %v", err)
	}
	if err := os.MkdirAll(workDirAbs, 0755); err != nil {
		log.Fatalf("Failed to create work directory: %v", err)
	}

	// 初始化通知器
	notifier := notification.NewNotifier(db)

	// 初始化执行器
	executor := executor.NewExecutor(db, notifier, workDirAbs)

	// 初始化API处理器
	apiHandler := api.NewHandler(db, executor)

	// 初始化Webhook处理器
	webhookHandler := webhook.NewWebhookHandler(db, executor, *webhookSecret)

	// 创建Gin路由器
	router := gin.New()

	// 添加中间件
	router.Use(gin.Logger())
	router.Use(gin.Recovery())

	// 添加CORS中间件
	router.Use(func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// 加载HTML模板
	router.LoadHTMLGlob("web/templates/*")

	// 设置静态文件服务
	router.Static("/static", "./web/static")

	// 前端页面路由
	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "Alfred CI/CD",
		})
	})

	// 设置API路由
	apiHandler.SetupRoutes(router)
	webhook.SetupWebhookRoutes(router, webhookHandler)

	// 启动服务
	log.Printf("Alfred CICD服务启动中...")
	log.Printf("端口: %s", *port)
	log.Printf("数据库: %s", *dbPath)
	log.Printf("工作目录: %s", workDirAbs)
	log.Printf("模式: %s", *mode)

	if *webhookSecret != "" {
		log.Printf("GitLab Webhook已启用")
	} else {
		log.Printf("警告: GitLab Webhook密钥未设置，webhook功能可能不安全")
	}

	log.Printf("服务已启动，访问 http://localhost:%s ", *port)

	if err := router.Run(":" + *port); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}
